package com.chen.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.dao.mapper.CourseMapper;
import com.chen.dao.mapper.CourseRecordMapper;
import com.chen.dao.pojo.Course;
import com.chen.dao.pojo.CourseRecord;
import com.chen.service.CourseService;
import com.chen.util.DateUtils;
import com.chen.util.FileUtils;
import com.chen.vo.CourseVo;
import com.chen.vo.Result;
import com.chen.vo.param.CourseParam;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author:chenao
 * @DATE:2022/3/11 22:43
 */
@Service
@Slf4j
public class CourseServiceImpl implements CourseService {
    @Autowired
    private FileUtils fileUtils;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private CourseRecordMapper courseRecordMapper;

    private final static String formatPattern="yyyy-MM-dd HH:mm:ss";

    @Override
    public Result saveCourse(MultipartFile file, Map<String, String> params) {
        if(isConflict(params)){

            return Result.fail(10006,"发布失败，课程冲突");
        }
        String[] courseDates = params.get("courseDate").split(",");
        String startTime= DateUtils.formatDateString(courseDates[0]);
        String endTime= DateUtils.formatDateString(courseDates[1]);
        Map<String, String> map = fileUtils.saveFile(file, "course");
        Course course = new Course();
        course.setCourseName(params.get("courseName"));
        course.setStartTime(startTime);
        course.setEndTime(endTime);
        course.setImageUrl(map.get("imageUrl"));
        course.setIntroduce(params.get("introduce"));
        course.setAddress(params.get("address"));
        course.setPersonNum(params.get("personNum"));
        course.setCategory(params.get("category"));
        course.setCoachId(params.get("coachId"));
        course.setPrice(params.get("price"));
        if (Strings.isNotBlank(params.get("id"))){
            course.setId(params.get("id"));
            courseMapper.updateById(course);
            return Result.success("修改成功");
        } else {
            courseMapper.insert(course);
            return Result.success("添加成功");
        }
    }

    @Override
    public Result listCourse(CourseParam param) {
        Page<Course> page = new Page<>(param.getPage(),param.getLimit());
        LambdaQueryWrapper<Course> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Course::getId,param.getId());
        //非空判断防止数据库有null值
        if (Strings.isNotBlank(param.getCourseName())){
            wrapper.like(Course::getCourseName,param.getCourseName());
        }
        if (Strings.isNotBlank(param.getCategory())){
            wrapper.like(Course::getCategory,param.getCategory());
        }
        if (Strings.isNotBlank(param.getCoachId())){
            wrapper.like(Course::getCoachId,param.getCoachId());
        }
        courseMapper.selectPage(page,wrapper);
        List<CourseVo> courseVoList = new LinkedList<>();
        page.getRecords().stream().forEach(item->{
            CourseVo courseVo = new CourseVo();
            BeanUtils.copyProperties(item,courseVo);

            String startTime= DateUtils.parseDateString(item.getStartTime());
            String endTime= DateUtils.parseDateString(item.getEndTime());
            String[] courseDate =new String[]{startTime,endTime};
            courseVo.setCourseDate(courseDate);
            courseVoList.add(courseVo);
        });
        return Result.success(courseVoList,page.getTotal());
    }

    @Override
    public Result deleteById(String id) {
        int i = courseMapper.deleteById(id);
        return Result.success(i);
    }

    @Override
    public Result statistic() {
        int count[] = new int[12];
        List<Course> courseList = courseMapper.selectList(null);
        courseList.stream().forEach(item->{
            DateTime parse = DateUtil.parse(item.getStartTime(), formatPattern);
            if (parse.year()==DateUtil.year(new Date())){
                count[parse.month()]++;
            }
        });
        return Result.success(count);
    }

    @Override
    public Result reserveStatis() {
        int count[] = new int[12];
        List<CourseRecord> courseList = courseRecordMapper.selectList(null);
        courseList.stream().forEach(item->{
            DateTime parse = DateUtil.parse(item.getEditTime(), formatPattern);
            if (parse.year()==DateUtil.year(new Date())){
                count[parse.month()]++;
            }
        });
        return Result.success(count);
    }

    private boolean isConflict(Map<String, String> params){
        //获取课程的开始结束时间
        boolean isConflict=false;
        String[] courseDates = params.get("courseDate").split(",");
        String startTime= DateUtils.formatDateString(courseDates[0]);
        String endTime= DateUtils.formatDateString(courseDates[1]);
        long pubStartTime = DateUtil.parse(startTime, formatPattern).getTime();
        long pubEndTime = DateUtil.parse(endTime, formatPattern).getTime();
        List<Course> courseList = courseMapper.selectList(null);
        for (Course item : courseList) {
            String endTime1 = item.getEndTime();
            String startTime1 = item.getStartTime();
            long originStartTime = DateUtil.parse(startTime1, formatPattern).getTime();
            long originEndTime = DateUtil.parse(endTime1, formatPattern).getTime();
            log.info("{}{}",originStartTime+originEndTime);
            //首先判断课程时间冲突情况
            if (pubEndTime<originStartTime || pubStartTime>originEndTime){
                //代表不冲突直接返回
                break;
            }
            //判断场地是否冲突
            if (params.get("address").equals(item.getAddress())){
                //时间和场地冲突就直接代表冲突
                isConflict=true;
            }
            if (params.get("coachId").equals(item.getCoachId())){
                //时间和教练就直接代表冲突
                isConflict=true;
            }
        }
        return isConflict;
    }

}
